package mymiddleware

import (
	"gf-xb-api/cwt/result"
	"gf-xb-api/internal/consts"
	"reflect"
	"time"

	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gmeta"
	"github.com/yudeguang/ratelimit"
)

// 权限中间件
type middlewareService struct{}

var middleware = middlewareService{}

func Middleware() *middlewareService {
	return &middleware
}

// CORS 跨源资源共享
func (s *middlewareService) CORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

var rule *ratelimit.Rule

// RequestIpLimit ip限制
func (s *middlewareService) RequestIpLimit(r *ghttp.Request) {
	ip := r.GetClientIp()
	if rule == nil {
		rule = ratelimit.NewRule()
		rule.AddRule(time.Hour, 10000)
		rule.AddRule(time.Minute, 600)
		rule.AddRule(time.Second, 60)
	}

	ok := rule.AllowVisit(ip)
	if !ok {
		r.Response.WriteJson(result.Fail(consts.JWT_ERR_ABNORMAL_ACCESS))
		r.ExitAll()
		return
	}

	r.Middleware.Next()
}

// isAnonymous ... 接口是否匿名
func isAnonymous(r *ghttp.Request) bool {
	reqObj := reflect.New(r.GetServeHandler().Handler.Info.Type.In(1)).Interface()
	return gmeta.Get(reqObj, consts.ALLOW_ANONYMOUS).Bool()
}

func (s *middlewareService) Auth(r *ghttp.Request) {
	if isAnonymous(r) {
		r.Middleware.Next()
		return
	}

	// GfJWTMiddleware gf jwt集成的中间件
	// Auth是权限service中配置的gf jwt
	Auth().MiddlewareFunc()(r)
	r.Middleware.Next()
}
